package com.xmkj.winmoney.jifen;

import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.common.Entity.HomeEntity;
import com.common.Entity.HtmlEntity;
import com.common.Entity.JingPaiEntity;
import com.common.Entity.ShareEntity;
import com.common.adapter.helper.IRecyclerViewHelper;
import com.common.banner.CBViewHolderCreator;
import com.common.banner.ConvenientBanner;
import com.common.base.Config;
import com.common.cons.Constans;
import com.common.mvp.BaseMvpActivity;
import com.common.mvp.BasePresenter;
import com.common.retrofit.method.GetHtmlMethods;
import com.common.retrofit.method.GetShareDatasMethods;
import com.common.retrofit.method.JingPaiDetailMethods;
import com.common.retrofit.method.ShareSuccessMethods;
import com.common.retrofit.subscriber.CommonSubscriber;
import com.common.retrofit.subscriber.SubscriberListener;
import com.common.rxbus.RxBus;
import com.common.rxbus.postevent.RxKeyEvent;
import com.common.utils.EmptyUtils;
import com.common.utils.SPUtils;
import com.common.utils.SizeUtils;
import com.common.utils.TimeUtils;
import com.common.widget.CountDown.CountdownView;
import com.common.widget.DividerDecoration.MarginDecoration;
import com.common.widget.recyclerview.refresh.recycleview.XRecyclerView;
import com.hyphenate.EMMessageListener;
import com.hyphenate.EMValueCallBack;
import com.hyphenate.chat.EMChatRoom;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMMessage;
import com.xmkj.payandlogin.ShareConfig;
import com.xmkj.payandlogin.ShareManager;
import com.xmkj.payandlogin.ShareUtil;
import com.xmkj.payandlogin.share.ShareListener;
import com.xmkj.payandlogin.share.SharePlatform;
import com.xmkj.winmoney.BaseUrlURLActivity;
import com.xmkj.winmoney.R;
import com.xmkj.winmoney.home.NetworkImageHolderView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import rx.functions.Action1;

/**
 * Create by leo
 * 创建日期：2018/5/18
 * 描述：
 */

public class JinPaiDetailActivity extends BaseMvpActivity {
    List<JingPaiEntity.AuctionInfoEntity> bean = new ArrayList<>();
    public static final String INFOBEAN = "infobean";
    public static final String TYPE = "type";
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.iv_share)
    ImageView ivShare;
    @BindView(R.id.home_view_pager)
    ConvenientBanner homeViewPager;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_info)
    TextView tvInfo;
    @BindView(R.id.tv_price)
    TextView tvPrice;
    @BindView(R.id.recyclerview)
    XRecyclerView recyclerview;
    @BindView(R.id.tv_records)
    TextView tvRecords;
    @BindView(R.id.iv_go)
    ImageView ivGo;
    @BindView(R.id.rl_photo_details)
    RelativeLayout rlPhotoDetails;
    @BindView(R.id.iv_goo)
    ImageView ivGoo;
    @BindView(R.id.rl_last)
    RelativeLayout rlLast;
    @BindView(R.id.iv_gooo)
    ImageView ivGooo;
    @BindView(R.id.rl_rule_jingpai)
    RelativeLayout rlRuleJingpai;
    @BindView(R.id.tv_go_next)
    TextView tvGoNext;
    @BindView(R.id.tv_get_jinbi)
    TextView tvGetJinbi;
    @BindView(R.id.tv_support)
    TextView tvSupport;
    @BindView(R.id.ll_on)
    LinearLayout llOn;
    @BindView(R.id.count_down)
    CountdownView countdownView;
    @BindView(R.id.tv_over)
    TextView tvOver;
    @BindView(R.id.rl_all_records)
    RelativeLayout rlAllRecords;
    @BindView(R.id.tv_qipai)
    TextView tvQipai;
    @BindView(R.id.tv_jiajia_rate)
    TextView tvJiajiaRate;
    @BindView(R.id.tv_shouxufeie)
    TextView tvShouxufeie;
    @BindView(R.id.tv_daojishi)
    TextView tvDaojishi;
    @BindView(R.id.tv_chajia_buy)
    TextView tvChajiaBuy;
    @BindView(R.id.tv_tuibi_rate)
    TextView tvTuibiRate;


    private HomeEntity.ListsEntity infoBean;
    private String type;
    private ChuJiaRecordAdapter adapter;
    private JingPaiEntity beans;
    private int[] page_indicatorId;
    private ShareEntity shareEntity;
    private boolean isNormolShare = true;

    @Override
    protected BasePresenter createPresenterInstance() {
        return null;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_jinpai_details;
    }

    @Override
    protected void onViewCreated() {
        infoBean = (HomeEntity.ListsEntity) getIntent().getSerializableExtra(INFOBEAN);
    }


    @Override
    protected void doLogicFunc() {
        ShareConfig config = ShareConfig.instance()
                .qqId(Config.APP_QQ_ID)
                .wxSecret(Config.APP_SERECET)
                .wxId(Config.APP_ID);
        ShareManager.init(config);
        getShareData();
        setRecyclerView();

        rxManager.add(RxBus.getDefault().toObservable(RxKeyEvent.class).subscribe(new Action1<RxKeyEvent>() {
            @Override
            public void call(RxKeyEvent rxKeyEvent) {
                if (EmptyUtils.isNotEventEmpty(rxKeyEvent, RxKeyEvent.JINGPAISUCEESS) && (Boolean) rxKeyEvent.getValue()) {
                    if (EmptyUtils.isNotEmpty(infoBean)) {
                        gotoHttpRep();
                    }

                }
            }
        }));
        if (EmptyUtils.isNotEmpty(infoBean)) {
            gotoHttpRep();
            if (EmptyUtils.isNotEmpty(infoBean.roomIds)) {
                //加入聊天室
                //roomId为聊天室ID
                EMClient.getInstance().chatroomManager().joinChatRoom(infoBean.roomIds, new EMValueCallBack<EMChatRoom>() {

                    @Override
                    public void onSuccess(EMChatRoom value) {
                        System.out.println("AAAASUCCESS" + value);
                        //加入聊天室成功
                    }

                    @Override
                    public void onError(final int error, String errorMsg) {
                        //加入聊天室失败
                        System.out.println("AAAAERROR" + errorMsg);
                    }
                });
                EMClient.getInstance().chatManager().addMessageListener(msgListener);


            }

        }
        attachClickListener(ivBack);
        attachClickListener(tvGoNext);
        attachClickListener(tvSupport);
        attachClickListener(ivShare);
        attachClickListener(rlAllRecords);
        attachClickListener(rlPhotoDetails);
        attachClickListener(rlLast);
        attachClickListener(tvGetJinbi);
        attachClickListener(rlRuleJingpai);

    }

    EMMessageListener msgListener = new EMMessageListener() {

        @Override
        public void onMessageReceived(List<EMMessage> messages) {
            //收到消息
            gotoHttpRep();
            System.out.println("WSWSSeede");
        }

        @Override
        public void onCmdMessageReceived(List<EMMessage> messages) {
            //收到透传消息
            gotoHttpRep();
            System.out.println("收到透传消息");
        }

        @Override
        public void onMessageRead(List<EMMessage> messages) {
            //收到已读回执
            gotoHttpRep();
            System.out.println("收到已读回执");
        }

        @Override
        public void onMessageDelivered(List<EMMessage> message) {
            //收到已送达回执\
            gotoHttpRep();
            System.out.println("收到已送达回执");
        }


        @Override
        public void onMessageChanged(EMMessage message, Object change) {
            //消息状态变动
            gotoHttpRep();
            System.out.println("消息状态变动");
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EMClient.getInstance().chatManager().removeMessageListener(msgListener);
    }

    private void getShareData() {
        CommonSubscriber<ShareEntity> subscriber = new CommonSubscriber<>(new SubscriberListener() {
            @Override
            public void onNext(Object o) {
                dismissProgressDialog();
                shareEntity = (ShareEntity) o;

//                gotoHttpRep();
            }

            @Override
            public void onError(String e, int code) {
                dismissProgressDialog();
                showToastMsg(e);
            }
        });
        GetShareDatasMethods.getInstance().share(subscriber, uid, hashid);
        rxManager.add(subscriber);
    }

    @Override
    protected void onViewClicked(View view) {
        if (view.getId() == ivBack.getId()) {
            onBackPressed();
        } else if (view.getId() == rlAllRecords.getId()) {
            Intent intent = new Intent(context, AllRecordActivity.class);
            intent.putExtra(AllRecordActivity.INFO, infoBean);
            startActivity(intent);
        } else if (view.getId() == tvGoNext.getId()) {
            if (EmptyUtils.isNotEmpty(beans.new_activity) && EmptyUtils.isNotEmpty(beans.new_activity.gid)) {
                Intent intent = new Intent(context, JinPaiDetailActivity.class);
                HomeEntity.ListsEntity item = new HomeEntity.ListsEntity();
                item.fvid = beans.new_activity.fvid;
                item.gid = Integer.valueOf(beans.new_activity.gid);
                item.vid = beans.new_activity.vid;
                intent.putExtra(JinPaiDetailActivity.INFOBEAN, item);
                startActivity(intent);
            } else {
                showToastMsg("敬请期待！");
            }

        } else if (view.getId() == rlPhotoDetails.getId()) { //图文详情
            Intent intent = new Intent(context, PhotoDetailsAcitivity.class);
            intent.putExtra(PhotoDetailsAcitivity.GID, infoBean.gid + "");
            startActivity(intent);
        } else if (view.getId() == ivShare.getId()) {
            isNormolShare = true;
            share();
        } else if (view.getId() == tvSupport.getId()) {
            Intent intent = new Intent(context, UseMoneyJoinAcitivity.class);
            intent.putExtra(UseMoneyJoinAcitivity.JIFEN, beans.good_info.single_score + "");
            intent.putExtra(UseMoneyJoinAcitivity.JINGPAIBEAN, infoBean);
            startActivity(intent);
        } else if (view.getId() == rlLast.getId()) {
            Intent intent = new Intent(context, JingPaiLastJieXiaoActivity.class);
            intent.putExtra(JingPaiLastJieXiaoActivity.GID, infoBean.gid + "");
            startActivity(intent);
        } else if (view.getId() == tvGetJinbi.getId()) {
            isNormolShare = false;
            share();
        } else if (view.getId() == rlRuleJingpai.getId()) {
            CommonSubscriber<HtmlEntity> subscriber = new CommonSubscriber<>(new SubscriberListener() {
                @Override
                public void onNext(Object o) {
                    dismissProgressDialog();
                    HtmlEntity entity = (HtmlEntity) o;

                    if (EmptyUtils.isNotEmpty(entity.guize)) {
                        Intent intent1 = new Intent(context, BaseUrlURLActivity.class);
                        intent1.putExtra(BaseUrlURLActivity.MAIN_URL, entity.guize);
                        intent1.putExtra(BaseUrlURLActivity.TITILE, "规则");
                        context.startActivity(intent1);
                    }
                }

                @Override
                public void onError(String e, int code) {
                    dismissProgressDialog();
                    showToastMsg(e);
                }
            });
            GetHtmlMethods.getInstance().h5(subscriber, uid, hashid);
            rxManager.add(subscriber);
        }
    }

    public void share() {
        showShareButton();
        setOnShareClick(new OnShareClick() {
            @Override
            public void wechat() {
                if (ShareUtil.isInstalled(SharePlatform.WX, context)) {

//                    Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), R.mipmap.icon);
//                    if (EmptyUtils.isEmpty(mineBean.img)) {
//                        ShareUtil.shareMedia(context, SharePlatform.WX, mineBean.title, mineBean.content, mineBean.url, bitmap, shareListener);
//
//                    } else {
//
//   ShareUtil.shareMedia(context, SharePlatform.WX, mineBean.title, mineBean.content, mineBean.url, mineBean.img, shareListener);
                    if (isNormolShare) {
                        ShareUtil.shareMedia(context, SharePlatform.WX, shareEntity.share_title.equals("") ? "拼夺宝" : shareEntity.share_title, shareEntity.share_content, shareEntity.share_url, shareEntity.logo, shareListener);

                    } else {
                        ShareUtil.shareImage(context, SharePlatform.WX, shareEntity.qr_code, shareListener);
                    }
//                    }
//                    ShareUtil.shareImage(context, SharePlatform.WX, shareEntity.qr_code, shareListener);

                } else {
                    showToastMsg("未安装微信");
                }
            }

            @Override
            public void wethatCircle() {
                if (ShareUtil.isInstalled(SharePlatform.WX_TIMELINE, context)) {
//                    Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), R.mipmap.icon);
//                    if (EmptyUtils.isEmpty(mineBean.img)) {
//                        ShareUtil.shareMedia(context, SharePlatform.WX_TIMELINE, mineBean.title, mineBean.content, mineBean.url, bitmap, shareListener);
//
//                    } else {
//                        ShareUtil.shareMedia(context, SharePlatform.WX_TIMELINE, mineBean.title, mineBean.content, mineBean.url, mineBean.img, shareListener);
                    if (isNormolShare) {
                        ShareUtil.shareMedia(context, SharePlatform.WX_TIMELINE, shareEntity.share_title.equals("") ? "拼夺宝" : shareEntity.share_title, shareEntity.share_content, shareEntity.share_url, shareEntity.logo, shareListener);

                    } else {
                        ShareUtil.shareImage(context, SharePlatform.WX_TIMELINE, shareEntity.qr_code, shareListener);
                    }
//                    }
//                    ShareUtil.shareImage(context, SharePlatform.WX_TIMELINE, shareEntity.qr_code, shareListener);
                } else {
                    showToastMsg("未安装微信");
                }
            }

            @Override
            public void qq() {
                if (ShareUtil.isInstalled(SharePlatform.QQ, context)) {
//                    Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), R.mipmap.icon);
               /*     if (EmptyUtils.isEmpty(mineBean.img)) {
                        ShareUtil.shareMedia(context, SharePlatform.QQ, mineBean.title, mineBean.content, mineBean.url, bitmap, shareListener);

                    } else {*/
//                        ShareUtil.shareMedia(context, SharePlatform.QQ, mineBean.title, mineBean.content, mineBean.url, mineBean.img, shareListener);
                    if (isNormolShare)
                        ShareUtil.shareMedia(context, SharePlatform.QQ, shareEntity.share_title.equals("") ? "拼夺宝" : shareEntity.share_title, shareEntity.share_content, shareEntity.share_url, shareEntity.logo, shareListener);
                    else
                        ShareUtil.shareImage(context, SharePlatform.QQ, shareEntity.qr_code, shareListener);
//                    }

                } else {
                    showToastMsg("未安装QQ");
                }
            }
        });
    }

    private ShareListener shareListener = new ShareListener() {
        @Override
        public void shareSuccess() {
            showToastMsg("分享成功");
            Sharesuccessfully();
        }

        @Override
        public void shareFailure(Exception e) {
            showToastMsg("分享失败");
        }

        @Override
        public void shareCancel() {
            showToastMsg("取消分享");
        }
    };

    private void Sharesuccessfully() {
        CommonSubscriber<Object> subscriber = new CommonSubscriber<>(new SubscriberListener() {
            @Override
            public void onNext(Object o) {
                dismissProgressDialog();

//                gotoHttpRep();
            }

            @Override
            public void onError(String e, int code) {
                dismissProgressDialog();
                showToastMsg(e);
            }
        });
        ShareSuccessMethods.getInstance().shareSuccess(subscriber, uid, hashid);
        rxManager.add(subscriber);
    }

    private int count;

    private void gotoHttpRep() {
        CommonSubscriber<JingPaiEntity> subscriber = new CommonSubscriber<>(new SubscriberListener() {

            @Override
            public void onNext(Object o) {
                ++count;
                dismissProgressDialog();
                beans = (JingPaiEntity) o;

                tvName.setText(beans.good_info.goods_name);
                tvInfo.setText(beans.good_info.goods_desc);
                tvPrice.setText(beans.good_info.goods_price);
                tvSupport.setText("出价" + beans.good_info.single_score + "金币/次");
                tvRecords.setText("全部出价记录" + beans.auction_total + "条");
                tvQipai.setText(beans.explain_table.starting_price);
                tvJiajiaRate.setText(beans.explain_table.price_increase);
                tvShouxufeie.setText(beans.explain_table.fee);
                tvDaojishi.setText(beans.explain_table.count_down);
                tvChajiaBuy.setText(beans.explain_table.differential_purchase);
                tvTuibiRate.setText(beans.explain_table.return_proportion);
                setBanner();


                if (beans.open_state == 2) {
                    countdownView.setVisibility(View.GONE);
                    tvOver.setVisibility(View.VISIBLE);
                    llOn.setVisibility(View.GONE);
                    tvGoNext.setVisibility(View.VISIBLE);
                } else {
                    countdownView.setVisibility(View.VISIBLE);
                    tvOver.setVisibility(View.GONE);
                    long time = TimeUtils.getStringToDate(beans.good_info.remainingdatestr) - TimeUtils.getStringToDate(beans.now_time);
                    countdownView.start(time);
                    llOn.setVisibility(View.VISIBLE);
                    tvGoNext.setVisibility(View.GONE);
                }

                if (count == 1) {
                    List<JingPaiEntity.AuctionInfoEntity> beanList = beans.auction_info;
                    recyclerview.loadMoreComplete();
                    // 下拉刷新
                    if (mIsRefreshOrLoadMore == 0) {
                        recyclerview.refreshComplete();
                        adapter.clear();
                    }

                    if (EmptyUtils.isNotEmpty(beanList)) {
                        bean = beanList;
                        adapter.addAll(bean);
                    } else if (mIsRefreshOrLoadMore == 0) {
//                    statusEmpty();
                        return;
                    }

                    if (EmptyUtils.isEmpty(beanList)) {
                        recyclerview.setNoMore(true);
                    } else {
                        mIsHasNoData = beanList.size() < mPageSize;
                        recyclerview.setNoMore(mIsHasNoData);
                    }
                    adapter.notifyDataSetChanged();
                    recyclerview.refreshComplete();
                    recyclerview.loadMoreComplete();
                    if (mIsRefreshOrLoadMore == 0) {
                        dismissProgressDialog();
                    }
                }
            }

            @Override
            public void onError(String e, int code) {
                dismissProgressDialog();
                adapter.notifyDataSetChanged();
                recyclerview.refreshComplete();
                recyclerview.loadMoreComplete();
                if (mIsRefreshOrLoadMore == 0) {
                    dismissProgressDialog();
                }
            }
        });

        if (EmptyUtils.isNotEmpty(infoBean)) {
            JingPaiDetailMethods.getInstance().jingpaiGoods(subscriber, SPUtils.getShareInt(Constans.UID), SPUtils.getShareString(Constans.HASHID), infoBean.gid + "", infoBean.vid + "", infoBean.fvid + "");
            rxManager.add(subscriber);
        }

    }

    private List<String> viewPagerUrl = new ArrayList<>();

    private void setBanner() {
//        viewPagerUrl.add("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1525427891333&di=32991d497454624b5c490151a185a2c1&imgtype=0&src=http%3A%2F%2Fimg.zcool.cn%2Fcommunity%2F0142135541fe180000019ae9b8cf86.jpg%401280w_1l_2o_100sh.png");
//        viewPagerUrl.add("http://img07.tooopen.com/images/20170316/tooopen_sy_201956178977.jpg");
//        viewPagerUrl.add("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1525427891333&di=32991d497454624b5c490151a185a2c1&imgtype=0&src=http%3A%2F%2Fimg.zcool.cn%2Fcommunity%2F0142135541fe180000019ae9b8cf86.jpg%401280w_1l_2o_100sh.png");
        if (beans != null && beans.good_info.goods_album.size() > 0 && viewPagerUrl.size() == 0) {
            for (int i = 0; i < beans.good_info.goods_album.size(); i++) {
                viewPagerUrl.add(beans.good_info.goods_album.get(i));
            }
        }
        page_indicatorId = new int[]{R.drawable.ic_page_indicator, R.drawable.ic_page_indicator_focused};
        homeViewPager.setPageIndicator(page_indicatorId);
        homeViewPager.setPages(new CBViewHolderCreator<NetworkImageHolderView>() {
            @Override
            public NetworkImageHolderView createHolder() {
                return new NetworkImageHolderView();
            }
        }, viewPagerUrl);
        homeViewPager.startTurning(5000);
    }

    private void setRecyclerView() {
//        IRecyclerViewHelper.init().setRecycleLineLayout(context, LinearLayoutManager.VERTICAL, recyclerview);
       /* GridLayoutManager layoutManager = new GridLayoutManager(context, 2);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerview.setLayoutManager(layoutManager);*/
        IRecyclerViewHelper.init().setRecycleLineLayout(context, LinearLayoutManager.VERTICAL, recyclerview);
        recyclerview.addItemDecoration(new MarginDecoration(LinearLayoutManager.VERTICAL, (int) SizeUtils.dp2px(context, 1)));
        recyclerview.setHasFixedSize(true);
        recyclerview.setRefreshing(false);
        recyclerview.setRefreshEnabled(false);
        recyclerview.setLoadMoreEnabled(false);
        adapter = new ChuJiaRecordAdapter(context, bean);
        recyclerview.setAdapter(adapter);
        recyclerview.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                mPageIndex = 1;
                mIsRefreshOrLoadMore = 0;
                gotoHttpRep();
            }

            @Override
            public void onLoadMore() {
                if (mIsHasNoData) {
                    recyclerview.loadMoreComplete();
                    recyclerview.setNoMore(true);
                    return;
                }
                mPageIndex++;
                mIsRefreshOrLoadMore = 1;
                gotoHttpRep();
            }
        });
    }

    @Override
    protected void setStatusBar() {

    }


    @Override
    public void bindKnife() {
        ButterKnife.bind(this);
    }


}
